package com.up.upzl.biz.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.up.upzl.biz.domain.ShopTag;
import com.up.upzl.biz.service.ShopTagService;

/**
 * 项目标签控制器
 * 
 * @author joker
 *
 */
@Controller
@RequestMapping("shopTag")
public class ShopTagController {

	@Autowired
	private ShopTagService shopTagService;

	/**
	 * 项目标签列表
	 * 
	 * @param name
	 *            关键字
	 * @param page
	 *            分页信息
	 * @return 项目标签分页数据
	 */
	@GetMapping("list")
	public String AppList(String name, Pageable page, Model model) {
		page = new PageRequest(page.getPageNumber(), page.getPageSize(), new Sort(Direction.DESC, "sort"));
		Page<ShopTag> list = null;
		if (StringUtils.isEmpty(name)) {
			list = shopTagService.findAll(page);
		} else {
			list = shopTagService.findByNameLike(name, page);
		}
		model.addAttribute("pageList", list);
		return "shopTag/list";
	}

	/**
	 * 跳转到添加页面
	 */
	@GetMapping("addPage")
	public String add(Model model) {
		return "shopTag/add";
	}

	/**
	 * 保存对象
	 */
	@PostMapping("add")
	public @ResponseBody ShopTag save(ShopTag shopTag) {
		return shopTagService.save(shopTag);
	}

	/**
	 * 跳转到更新页面
	 */
	@GetMapping({ "updatePage", "detail" })
	public String update(Long id, Model model) {
		ShopTag shopTag = shopTagService.findOne(id);
		model.addAttribute("entity", shopTag);
		List<ShopTag> Apps = shopTagService.findAll();
		model.addAttribute("Apps", Apps);
		return "shopTag/update";
	}

	/**
	 * 更新
	 */
	@PostMapping("update")
	public @ResponseBody ShopTag update(ShopTag shopTag) {
		Assert.notNull(shopTag.getId(), "Id can`t be null");
		return shopTagService.save(shopTag);
	}

	/**
	 * 删除
	 */
	@PostMapping("delete")
	public @ResponseBody Map<String, String> delete(ShopTag shopTag) {
		Assert.notNull(shopTag.getId(), "Id can`t be null");
		Map<String, String> map = new HashMap<>();
		Integer shopNum = shopTagService.countShopByShopTag(shopTag.getId());
		if (shopNum > 0) {
			map.put("Type", "201");
		} else {
			try {
				shopTagService.delete(shopTag.getId());
				map.put("Type", "200");
			} catch (Exception e) {
				map.put("Type", "500");
				return map;
			}
		}
		return map;
	}

}
